package com.spacex.danhuang.polive.activities;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.spacex.danhuang.polive.Application.VApplication;
import com.spacex.danhuang.polive.Constants.Constants;
import com.spacex.danhuang.polive.R;

import org.json.JSONException;
import org.json.JSONObject;

import io.socket.client.Socket;
import io.socket.emitter.Emitter;

public class LoginActivity extends BaseActivity {
    private static final String TAG = "LoginActivity";

    private EditText et_inputUserid;
    private EditText et_inputNickname;
    private EditText et_inputSex;
    private Button bt_login;

    private VApplication app;
    private Socket mSocket;

    private String mUserid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        app = (VApplication)getApplication();
        mSocket = app.getSocket();
        mSocket.on("message", onHandleMsg);

        initView();

        bt_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                attemptLogin();
            }
        });
    }

    private void initView() {
        et_inputUserid = (EditText)findViewById(R.id.et_login_input_userid);
        et_inputNickname = (EditText)findViewById(R.id.et_login_input_nickname);
        et_inputSex = (EditText)findViewById(R.id.et_login_input_sex);
        bt_login = (Button)findViewById(R.id.bt_login_login);
    }

    private int checkIsValid(String userid, String nickname, int sex) {

        if (TextUtils.isEmpty(userid)) {
            et_inputUserid.setError("user id cannot be empty");
            et_inputUserid.requestFocus();
            return Constants.FAILURE;
        }
        if (TextUtils.isEmpty(nickname)) {
            et_inputNickname.setError("nickname cannot be empty");
            et_inputNickname.requestFocus();
            return Constants.FAILURE;
        }
        if ((Constants.USER_SEX_FEMAIL != sex) && (Constants.USER_SEX_MAIL != sex)) {
            et_inputSex.setError("sex is error");
            et_inputSex.requestFocus();
            return Constants.FAILURE;
        }

        return Constants.SUCCESS;
    }

    private void attemptLogin() {

        String userId = et_inputUserid.getText().toString().trim();
        String nickName = et_inputNickname.getText().toString().trim();
        int sex = Integer.parseInt(et_inputSex.getText().toString().trim());
        Log.i(TAG, String.format("sex = %d", sex));

        if (Constants.SUCCESS != checkIsValid(userId, nickName, sex)) {
            Log.i(TAG, "输入有误");
            return;
        }

        mUserid = userId;

        JSONObject attemptLoginJSON = new JSONObject();
        JSONObject attemptLoginData = new JSONObject();
        try {
            attemptLoginJSON.put("request", Constants.LOGIN_NAME);

            attemptLoginData.put("userid", userId);
            attemptLoginData.put("nickname", nickName);
            attemptLoginData.put("sex",sex);
            attemptLoginJSON.put("data", attemptLoginData);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        String tmpLoginStr = attemptLoginJSON.toString();
        Log.i(TAG, "login send");
        Log.i(TAG, tmpLoginStr);
        mSocket.send(tmpLoginStr);
    }

    /**
     * Socket事件监听处理函数（收到"message"事件时触发）
     **/
    protected Emitter.Listener onHandleMsg = new Emitter.Listener() {
        @Override
        public void call(Object... args) {
            Log.i(TAG, "onHandleMsg received data");

            String onHandleMsgStr = (String)args[0];
            Log.i(TAG, onHandleMsgStr);
            JSONObject onHandleMsgJSON = null;
            try {
                onHandleMsgJSON = new JSONObject(onHandleMsgStr);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            String rsp_name = "";
            int rsp_status = 0;
            String rsp_errmsg = "";

            JSONObject onHandleMsgData = null;

            try {
                if (onHandleMsgJSON != null) {
                    rsp_name = onHandleMsgJSON.getString("response");
                    rsp_status = onHandleMsgJSON.getInt("status");
                    rsp_errmsg = onHandleMsgJSON.getString("errormsg");
                    Log.i(TAG, String.format("activity rsp_name = %s", rsp_name));
                    Log.i(TAG, String.format("rsp_status = %d", rsp_status));
                    Log.i(TAG, String.format("rsp_errmsg = %s", rsp_errmsg));

                    onHandleMsgData = onHandleMsgJSON.getJSONObject("data");
                }

            } catch (JSONException e) {
                e.printStackTrace();
                return;
            }

            handleSwitchMethod(rsp_name, rsp_status, rsp_errmsg, onHandleMsgData);
        }
    };

    protected void handleSwitchMethod(String rsp_name, int rsp_status, String rsp_errmsg, JSONObject onHandleMsgData) {
        switch (rsp_name) {
            case Constants.LOGIN_NAME:
                Log.i(TAG, "login result rev");
                handleLogin(rsp_status, rsp_errmsg);
                break;
            default:
                Log.i(TAG, "no rsp name");
        }
    }

    private void handleLogin(final int status, final String errmsg) {
        LoginActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (status != 0) {
                    Toast.makeText(LoginActivity.this.getApplicationContext(),
                            "ERROR: "+errmsg, Toast.LENGTH_SHORT).show();
                    Log.i(TAG, errmsg);
                    return;
                }

                app.setUserId(mUserid);
                app.setUserRole(Constants.USER_COMMON);  //设置用户权限为 普通用户

                Log.i(TAG, "go to AppMainActivity");
                Intent intent = new Intent();
                setResult(RESULT_OK, intent);
                finish();
            }
        });
    }
}
